# coding=utf-8
from Database_Config import *
from Ruler_Area_Define import *
from Recommend_Normal_By_Ruler import *
from Recommend_Abnormal_By_Ruler_New import *
import traceback
import random
#初始化正常卷的返回标志位
FLAG = '1000#'

# x轴宽度，y轴外径
# 判断钢卷号是否存在
def has_coil_database(table_name, coil_no):
    try:
        sql = "SELECT * FROM %s WHERE MAT_NO='%s'"%(table_name, coil_no)
        c = conn_ibm_dbi.cursor()
        c.execute(sql)
        rows = c.fetchall()
        return rows
    except Exception, ex:
        errorLogger.error("has_coil_database"+str(ex))
        errorLogger.error('error line:' + traceback.print_exc())


# 读取库图数据库中的相应小区域的钢卷占位状态，即读取区域名字相同的且状态位为2或者3的钢卷状态，UACS_YARDMAP_STOCK_DEFINE
# 应该要根据C02库区的鞍座编码形式来修改查询的语句
# C02的库位编码格式为：C02A1011   3位库区代码+2位列号+2位行号+1位层号
def read_behind_stock_status(table_name, row_start, row_end, col_start, col_end):
    try:
        sql = "SELECT X_CENTER,Y_CENTER,COIL_NO FROM %s WHERE SUBSTR(STOCK_NO,4,2) BETWEEN '%s' AND '%s' " \
              "AND SUBSTR(STOCK_NO,6,2) BETWEEN '%s' AND '%s' AND STOCK_STATUS!='1' " % (table_name, col_start,
                                                                                       col_end, row_start, row_end)
        c = conn_ibm_dbi.cursor()
        c.execute(sql)
        rows = c.fetchall()
        if len(rows)!=0:
            return rows
        else :
            return  False
    except Exception, ex:
        errorLogger.error("read_behind_stock_status" + str(ex))
        errorLogger.error('error line:' + traceback.print_exc())


# 根据钢卷号，读取钢卷信息库中，钢卷的宽度，直径，重量、是否为过渡卷，是否为废卷
def read_coil_database(table_name, coil_no):
    try:
        sql = "SELECT WIDTH,OUTDIA,ACT_WEIGHT,DUMMY_COIL_FLAG,NEXT_UNIT_NO,SCRAP_MAT_FLAG FROM %s WHERE MAT_NO='%s'" % (table_name, coil_no)
        c = conn_ibm_dbi.cursor()
        c.execute(sql)
        rows = c.fetchall()
        # 如果钢卷信息表中没有该材料号，则返回null
        if len(rows) == 0:
            return False
        else:
            return rows[0]
    except Exception, ex:
        errorLogger.error("read_coil_database" + str(ex))
        errorLogger.error('error line:' + traceback.print_exc())


# 根据鞍座坐标返回鞍座号
def select_saddle_no(table_name, center_x, center_y):
    try:
        sql = "SELECT STOCK_NO FROM %s WHERE X_CENTER= %d AND Y_CENTER = %d " % (table_name, center_x, center_y)
        c = conn_ibm_dbi.cursor()
        c.execute(sql)
        rows = c.fetchall()
        return rows[0][0]
    except Exception, ex:
        errorLogger.error("selct_saddle_no" + str(ex))
        errorLogger.error('error line:' + traceback.print_exc())


# 强制推荐的库位列表，找寻库区中空的鞍座，并保存在列表中
def force_choose_stock_list(table_name):
    try:
        new_force_choose_stock_list=[]
        sql = "SELECT STOCK_NO FROM %s WHERE STOCK_STATUS='1'AND ENABLE='1' AND STOCK_DIV='1' ORDER BY COL_ROW_NO ASC,STOCK_NO ASC" % (
            table_name)
        c = conn_ibm_dbi.cursor()
        c.execute(sql)
        rows = c.fetchall()
        # 如果有空余的鞍座号
        if len(rows) == 0:
            return 'null'
        else:
            for item in rows:
                new_force_choose_stock_list.append(item[0])
            return new_force_choose_stock_list
    except Exception, ex:
        errorLogger.error("force_choose_stock" + str(ex))
        errorLogger.error('error line:' + traceback.print_exc())


# 读取库图数据库中的前后排占位、预定的鞍座上的钢卷号，UACS_YARDMAP_STOCK_DEFINE
def read_coil_no(table_name, stock_no):
    try:
        sql = "SELECT  COIL_NO  FROM %s WHERE STOCK_NO='%s' AND STOCK_STATUS!='1'" % (
            table_name, stock_no)
        c = conn_ibm_dbi.cursor()
        c.execute(sql)
        rows = c.fetchall()
        if len(rows) == 0:
            return False
        else:
            return rows[0][0]
    except Exception, ex:
        errorLogger.error("read_coil_no" + str(ex))
        errorLogger.error('error line:' + traceback.print_exc())

# 根据所选择鞍座号，判断前后左右的钢卷是否相交，且要保证钢卷所在鞍座满足夹钳的安全距离
# 判断前后排鞍座上的钢卷宽度方向上是否满足
# def choose_satisfied_all_saddle(stock_result_list, coil_width, coil_outdia):
#     global FLAG
#     for item in stock_result_list:
#         select_stock_no = item
#         # 推荐的鞍座的x坐标
#         select_stock_coordinate= read_stock_coordinate(STOCK_INFORMATION_DATABASE, select_stock_no)
#         select_stock_x = select_stock_coordinate[0]
#         select_stock_y = select_stock_coordinate[1]
#         # 被推荐的钢卷放置在该鞍座上的RECT
#         recommend_rect = RECT( llp=POINT(select_stock_x - coil_width / 2., select_stock_y- coil_outdia / 2.),
#                             length=float(coil_outdia), width=float(coil_width))
#         # 拆分鞍座号
#         bay = select_stock_no[0:3]
#         row = select_stock_no[3:5]
#         col = select_stock_no[5:7]
#         flag = select_stock_no[-1]
#         row_front = int(row) - 1
#         row_back = int(row) + 1
#         col_left = int(col)-1
#         col_right = int(col)+1
#         # 计算的前一排的鞍座号
#         stock_no_front = bay + str(row_front).zfill(2) + col + flag
#         # 判断前排鞍座号是否存在
#         if has_stock_no(STOCK_INFORMATION_DATABASE, stock_no_front) == True:
#             # 若存在，返回该鞍座号
#             stock_no_front = bay + str(row_front).zfill(2) + col + flag
#         else:
#             stock_no_front = None
#         # 计算的后一排的鞍座号
#         stock_no_back = bay + str(row_back).zfill(2) + col + flag
#         # 判断后一排的鞍座号是否存在
#         if has_stock_no(STOCK_INFORMATION_DATABASE, stock_no_back) == True:
#             # 若存在，返回该鞍座号
#             stock_no_back = bay + str(row_back).zfill(2) + col + flag
#         else:
#             stock_no_back = None
#         # 计算的左边的鞍座号
#         stock_no_left = bay + row + str(col_left).zfill(2) + flag
#         # 判断左边的鞍座号是否存在
#         if has_stock_no(STOCK_INFORMATION_DATABASE, stock_no_left) == True:
#             # 若存在，返回该鞍座号
#             stock_no_left = bay + row + str(col_left).zfill(2) + flag
#         else:
#             stock_no_left = None
#         # 计算的右边的鞍座号
#         stock_no_right = bay + row + str(col_right).zfill(2) + flag
#         # 判断右边的鞍座号是否存在
#         if has_stock_no(STOCK_INFORMATION_DATABASE, stock_no_right) == True:
#             # 若存在，返回该鞍座号
#             stock_no_right = bay + row + str(col_right).zfill(2) + flag
#         else:
#             stock_no_right = None
#         # 读取前一排鞍座的坐标
#         if stock_no_front != None:
#             front_stock_coordiante= read_stock_coordinate(STOCK_INFORMATION_DATABASE, stock_no_front)
#             # 前排鞍座的x坐标
#             front_stock_x = front_stock_coordiante[0]
#             # 前排鞍座的y坐标
#             front_stock_y = front_stock_coordiante[1]
#         # 读取后一排鞍座的坐标
#         if stock_no_back != None:
#             back_stock_coordiante = read_stock_coordinate(STOCK_INFORMATION_DATABASE, stock_no_back)
#             # 后排鞍座的x坐标
#             back_stock_x = back_stock_coordiante[0]
#             # 后排鞍座的y坐标
#             back_stock_y = back_stock_coordiante[1]
#         # 读取左一列的鞍座的坐标
#         if stock_no_left != None:
#             left_stock_coordiante = read_stock_coordinate(STOCK_INFORMATION_DATABASE, stock_no_left)
#             # 后排鞍座的x坐标
#             left_stock_x = left_stock_coordiante[0]
#             # 后排鞍座的y坐标
#             left_stock_y = left_stock_coordiante[1]
#         # 读取右一列的鞍座的坐标
#         if stock_no_right != None:
#             right_stock_coordiante = read_stock_coordinate(STOCK_INFORMATION_DATABASE, stock_no_right)
#             # 后排鞍座的x坐标
#             right_stock_x = right_stock_coordiante[0]
#             # 后排鞍座的y坐标
#             right_stock_y = right_stock_coordiante[1]
#         # 读取前、后、左、右的鞍座上占座的钢卷信息
#         # 读取前一排占座或者预定的钢卷号
#         front_coil_number = read_coil_no(STOCK_INFORMATION_DATABASE, stock_no_front)
#         if front_coil_number!= False:
#             # 前一排占座的钢卷号
#             front_coil_no = front_coil_number
#         else:
#             front_coil_no = None
#         # 读取后一排占座或者预定的钢卷号
#         back_coil_number = read_coil_no(STOCK_INFORMATION_DATABASE, stock_no_back)
#         if back_coil_number != False:
#             # 后一排占座的钢卷号
#             back_coil_no = back_coil_number
#         else:
#             back_coil_no = None
#         # 读取左边一排占座或者预定的钢卷号
#         left_coil_number = read_coil_no(STOCK_INFORMATION_DATABASE, stock_no_left)
#         if left_coil_number != False:
#             # 左一排占座的钢卷号
#             left_coil_no = left_coil_number
#         else:
#             left_coil_no = None
#         # 读取右边一排占座或者预定的钢卷号
#         right_coil_number = read_coil_no(STOCK_INFORMATION_DATABASE, stock_no_left)
#         if right_coil_number != False:
#             # 左一排占座的钢卷号
#             right_coil_no = right_coil_number
#         else:
#             right_coil_no = None
#         # 依据前面一排、后面一排、左边一列，右边一列鞍座上的钢卷号读取其宽度和外径，判断是否相交
#         # 前一排鞍座上的钢卷的宽度、外径
#         if front_coil_no != None:
#             front_coil_information = read_coil_database(COIL_INFORMATION_DATABASE, front_coil_no)
#             if front_coil_information != False:
#                 front_coil_width = front_coil_information[0]
#                 front_coil_outdia = front_coil_information[1]
#             else:
#                 FLAG = '1004#'
#                 continue
#         else:
#             front_coil_width = 0
#             front_coil_outdia = 0
#         front_rect = RECT(llp=POINT(front_stock_x - front_coil_width/ 2., front_stock_y - front_coil_outdia / 2.),
#                             length=float(front_coil_outdia), width=float(front_coil_width))
#         # 后一排鞍座上的钢卷的宽度、外径
#         if back_coil_no != None:
#             back_coil_information = read_coil_database(COIL_INFORMATION_DATABASE, back_coil_no)
#             if back_coil_information != False:
#                 back_coil_width = back_coil_information[0]
#                 back_coil_outdia = back_coil_information[1]
#             else:
#                 FLAG = '1004#'
#                 continue
#         else:
#             back_coil_width = 0
#             back_coil_outdia = 0
#         back_rect = RECT(llp=POINT(back_stock_x - back_coil_width/ 2., back_stock_y - back_coil_outdia / 2.),
#                             length=float(back_coil_outdia), width=float(back_coil_width))
#         # 左边一排鞍座上的钢卷宽度、外径
#         if left_coil_no != None:
#             left_coil_information = read_coil_database(COIL_INFORMATION_DATABASE, left_coil_no)
#             if left_coil_information != False:
#                 left_coil_width = left_coil_information[0]
#                 left_coil_outdia = left_coil_information[1]
#             else:
#                 FLAG = '1004#'
#                 continue
#         else:
#             left_coil_width = 0
#             left_coil_outdia = 0
#         left_rect = RECT(llp=POINT(left_stock_x - left_coil_width / 2., left_stock_y - left_coil_outdia / 2.),
#              length=float(left_coil_outdia), width=float(left_coil_width))
#         # 右边一排鞍座上的钢卷宽度、外径
#         if right_coil_no != None:
#             right_coil_information = read_coil_database(COIL_INFORMATION_DATABASE, right_coil_no)
#             if right_coil_information != False:
#                 right_coil_width = right_coil_information[0]
#                 right_coil_outdia = right_coil_information[1]
#             else:
#                 FLAG = '1004#'
#                 continue
#         else:
#             right_coil_width = 0
#             right_coil_outdia = 0
#         right_rect = RECT(llp=POINT(right_stock_x - right_coil_width / 2., right_stock_y - right_coil_outdia / 2.),
#              length=float(right_coil_outdia), width=float(right_coil_width))
#         rect_list=[front_rect,back_rect,left_rect,right_rect]
#         #比较被推荐的钢卷与前后左右的钢卷是否相交
#         cross_flag,cross_rect = cross_rect_list(recommend_rect,rect_list)
#         # 没有矩形相交，则再比较前后的鞍座上的钢卷宽度是否满足夹钳打开的安全距离
#         if cross_flag:
#             # 如果没有前排鞍座，则比较与后排鞍座之间的钢卷宽度
#             if stock_no_front == None:
#                 # 推荐的鞍座上的钢卷与后一排鞍座上的钢卷的间距差
#                 back_stock_difference = abs(select_stock_x - back_stock_x) - (back_coil_width + coil_width) / 2
#                 if back_stock_difference >= MAX_SPACE:
#                     return FLAG + select_stock_no
#                 else:
#                     infoLogger.info( "Distance of the %s saddle and the behind is small!" % select_stock_no
#                     continue
#             # 如果没有后排鞍座，则比较与前排鞍座之间的钢卷宽度
#             if stock_no_back == None:
#                 # 推荐的鞍座上的钢卷与前一排鞍座上的钢卷的间距差
#                 front_stock_difference = abs(front_stock_x - select_stock_x) - (front_coil_width + coil_width) / 2
#                 if front_stock_difference >= MAX_SPACE:
#                     return FLAG + select_stock_no
#                 else:
#                     infoLogger.info( "Distance of the %s saddle and the front is small!" % select_stock_no
#                     continue
#             # 如果前后排都有鞍座，则都比较：
#             if stock_no_front != None and stock_no_back != None:
#                 # 推荐的鞍座上的钢卷与前一排鞍座上的钢卷的间距差
#                 front_stock_difference = abs(front_stock_x - select_stock_x) - (front_coil_width + coil_width) / 2
#                 # 推荐的鞍座上的钢卷与后一排鞍座上的钢卷的间距差
#                 back_stock_differce = abs(select_stock_x - back_stock_x) - (back_coil_width + coil_width) / 2
#                 if front_stock_difference >= MAX_SPACE and back_stock_differce >= MAX_SPACE:
#                     return FLAG + select_stock_no
#                 else:
#                     infoLogger.info( "Distance of the %s saddle and the behind,front is small!" % select_stock_no
#                     continue
#         # 有矩形相交，说明该鞍座不符合要求，则需要继续寻找
#         else:
#             infoLogger.info( "The stock is crossed with others!"
#             continue


# 主函数
# 上游传递给我钢卷号，外部指令，先根据这些参数，判断条件类型 table_name应该是UACS_YARDMAP_AREA_DEFINE
# C02库区的库位推荐依据direction来决定是调用一座一物的程序(direction=1)还是调用几何优化算法程序(direction=2)


def recommend_stock_position(coil_no, receive_string):
    global FLAG
    try: 
        return '1000#EY717H1'
        # 申请库位推荐的钢卷号
        infoLogger.info("recommend coil no is:%s" % (coil_no))
        # 接收到的外部指令
        infoLogger.info("receive string is:%s" % (receive_string))
        # 拆分外部传入的字符串，得出相应的条件判断信息
        receive_value = receive_string.split(',')
        # 跨号
        Bay_No = receive_value[0]
        # 如果跨号不存在，则返回1005
        if Bay_No != Bay_C02:
            infoLogger.info("Bay no is incorrect!")
            infoLogger.info('1005#Error')
            return '1005#Error'
        infoLogger.info('recommend stock start')
        #判断被推荐的钢卷号在钢卷信息表中是否存在
        recommend_coil_no = has_coil_database(COIL_INFORMATION_DATABASE, coil_no)
        # 被推荐的钢卷号在钢卷信息表中不存在
        if len(recommend_coil_no) == 0:
            infoLogger.info('this coil not exist in UACS_SCHEDULE_COIL')
            infoLogger.info('1003#Error')
            return '1003#Error'
        else:
            infoLogger.info('read coil information from UACS_SCHEDULE_COIL')
            recommend_coil_information = read_coil_database(COIL_INFORMATION_DATABASE, coil_no)
            infoLogger.info(recommend_coil_information)
            # 根据钢卷号读取钢卷信息，钢卷宽度、外径，重量
            width = recommend_coil_information[0]
            external_diameter = recommend_coil_information[1]
            weight = recommend_coil_information[2]
            # 下道机组号
            next_unit = recommend_coil_information[4]
            # 废卷标志
            scrap_mat_flag = recommend_coil_information[5]
           # 根据信息，判断条件类型
            condition_result = estimate_condition(external_diameter,weight,next_unit,scrap_mat_flag,receive_string)
            infoLogger.info(condition_result)
            # 配置文件中所写的库位推荐的规则中没有符合的条件类型
            if condition_result == None:
                infoLogger.info('this coil has no recommend stock ruler')
                # 被推荐的钢卷无库位推荐规则->强制推荐一个满足夹钳吊运的鞍座位置
                FLAG = '1001#'
                infoLogger.info('force recommend a suitable stock')
                choose_force_stock_list = force_choose_stock_list(STOCK_INFORMATION_DATABASE)
                infoLogger.info(choose_force_stock_list)
                # 库区已满，没有鞍座
                if choose_force_stock_list =='null':
                    infoLogger.info('force recommend empty stock,but no empty stock')
                    FLAG='1010#'
                    infoLogger.info(FLAG + 'Error')
                    return FLAG+'Error'
                # 有空余鞍座
                else:
                    # 一座一物的鞍座列表
                    choose_normal_stock_list =list()
                    # 波浪形鞍座列表
                    choose_abnormal_stock_list = list()
                    for stock_no in choose_force_stock_list:
                        # 鞍座的列号
                        col = stock_no[3:5]
                        if col in ["D1","E1","E2","E3","E4","H7","H8"]:
                            choose_abnormal_stock_list.append(stock_no)
                        else:
                            choose_normal_stock_list.append(stock_no)
                    # 强制推荐一个满足要求的空余鞍座
                    infoLogger.info("1.force recommend normal stock")
                    infoLogger.info(choose_normal_stock_list)
                    # 如果有空余的一座一物的鞍座
                    if len(choose_normal_stock_list)!=0:
                        # 选择一个合适的鞍座
                        choose_force_flag_stock = choose_satisfied_width_saddle(choose_normal_stock_list, width)
                        # 没有满足要求的空余鞍座
                        if choose_force_flag_stock =='null':
                            # 库区里没有合适的鞍座
                            infoLogger.info('force recommend empty normal stock,exist empty stock,but no suitable stock')
                            # 强制推荐一个波浪形鞍座
                            infoLogger.info("2.force recommend abnormal stock")
                            infoLogger.info(choose_abnormal_stock_list)
                            # 如果有空余的波浪形鞍座
                            if len(choose_abnormal_stock_list)!=0:
                                choose_force_wave_stock = choose_satisfied_wave_saddle(choose_abnormal_stock_list,external_diameter)
                                # 如果该卷所能放置的波浪形鞍座都放满
                                if choose_force_wave_stock == []:
                                    infoLogger.info("can not find suitable wave stock")
                                    FLAG = '1011#'
                                    infoLogger.info(FLAG + 'Error')
                                    return FLAG+'Error'
                                else:
                                    FLAG = choose_force_wave_stock.split('#')[0] + '#'
                                    recommend_stock_no = choose_force_wave_stock.split('#')[1]
                                    FLAG = '1000#'
                                    infoLogger.info(FLAG + recommend_stock_no)
                                    return FLAG + recommend_stock_no
                            # 如果没有空余的波浪形鞍座
                            else:
                                infoLogger.info("has no empty wave stock")
                                FLAG = '1010#'
                                infoLogger.info(FLAG + 'Error')
                                return FLAG + 'Error'
                        else:
                            choose_force_stock = choose_force_flag_stock.split('#')[1]
                            infoLogger.info(FLAG + choose_force_stock)
                            FLAG = '1000#'
                            infoLogger.info(FLAG + choose_force_stock)
                            return FLAG + choose_force_stock
                    else:
                      # 如果没有一座一物的鞍座
                        infoLogger.info("has no empty normal stock")
                        infoLogger.info("2.force recommend abnormal stock")
                        infoLogger.info(choose_abnormal_stock_list)
                        # 如果有空余的波浪形鞍座
                        if len(choose_abnormal_stock_list) != 0:
                            choose_force_wave_stock = choose_satisfied_wave_saddle(choose_abnormal_stock_list,
                                                                                   external_diameter)
                            # 如果该卷所能放置的波浪形鞍座都放满
                            if choose_force_wave_stock == []:
                                infoLogger.info("can not find suitable wave stock")
                                FLAG = '1011#'
                                infoLogger.info(FLAG + 'Error')
                                return FLAG + 'Error'
                            else:
                                FLAG = choose_force_wave_stock.split('#')[0] + '#'
                                recommend_stock_no = choose_force_wave_stock.split('#')[1]
                                FLAG = '1000#'
                                infoLogger.info(FLAG + recommend_stock_no)
                                return FLAG + recommend_stock_no
                        # 如果没有空余的波浪形鞍座
                        else:
                            infoLogger.info("has no empty wave stock")
                            FLAG = '1010#'
                            infoLogger.info(FLAG + 'Error')
                            return FLAG + 'Error'
            # 外部传入指令错误，抛出报警信息
            if len(condition_result)== 10:
                infoLogger.info('receive string has wrong info')
                infoLogger.info(condition_result)
                return condition_result
            # 正常条件类型
            condition_kind = condition_result[0]
            put_direction = condition_result[1]
            infoLogger.info("condition_kind is %s"%(condition_kind))
            # direction = 1是一座一物的鞍座摆放方式
            if put_direction == 1:
                recommend_result = recommend_area_by_ruler(condition_kind, put_direction, width,external_diameter)
                if recommend_result == None:
                    FLAG = '1010#'
                    infoLogger.info(FLAG + 'Error')
                    return FLAG + 'Error'
                elif  recommend_result =='null':
                    FLAG = '1011#'
                    infoLogger.info(FLAG + 'Error')
                    return FLAG + 'Error'
                else:
                    FLAG = recommend_result.split('#')[0] + '#'
                    recommend_stock_no = recommend_result.split('#')[1]
                    infoLogger.info(FLAG + recommend_stock_no)
                    FLAG = '1000#'
                    infoLogger.info(FLAG + recommend_stock_no)
                    return FLAG + recommend_stock_no
            # direction = 2是波浪形鞍座堆放
            if put_direction == 2:
                recommend_result=recommend_wave_area_by_ruler(condition_kind,put_direction,width,external_diameter)
                # 如果该卷所能放置的波浪形鞍座都放满
                if recommend_result==[]:
                    infoLogger.info("these wave area are full,so force a empty stock")
                    FLAG = '1010#'
                    # 强制推荐一个空余鞍座
                    choose_force_stock_list = force_choose_stock_list(STOCK_INFORMATION_DATABASE)
                    infoLogger.info(choose_force_stock_list)
                    # 库区已满，没有鞍座
                    if choose_force_stock_list == 'null':
                        infoLogger.info('force recommend empty stock,but no empty stock')
                        FLAG = '1010#'
                        infoLogger.info(FLAG + 'Error')
                        return FLAG + 'Error'
                    # 有空余鞍座
                    else:
                        # # 强制推荐一个满足要求的空余鞍座
                        # choose_force_flag_stock = choose_satisfied_width_saddle(choose_force_stock_list, width)
                        # # 没有满足要求的空余鞍座
                        # if choose_force_flag_stock == 'null':
                        #     # 库区里没有合适的鞍座
                        #     infoLogger.info('force recommend empty stock,exist empty stock,but no suitable stock')
                        #     FLAG = '1011#'
                        #     infoLogger.info(FLAG+'Error')
                        #     return FLAG + 'Error'
                        # else:
                        #     choose_force_stock = choose_force_flag_stock.split('#')[1]
                        #     infoLogger.info(FLAG + choose_force_stock)
                        #     FLAG = '1000#'
                        #     infoLogger.info(FLAG + choose_force_stock)
                        #     return FLAG + choose_force_stock
                        # 一座一物的鞍座列表
                        choose_normal_stock_list = list()
                        # 波浪形鞍座列表
                        choose_abnormal_stock_list = list()
                        for stock_no in choose_force_stock_list:
                            # 鞍座的列号
                            col = stock_no[3:5]
                            if col in ["D1", "E1", "E2", "E3", "E4", "H7", "H8"]:
                                choose_abnormal_stock_list.append(stock_no)
                            else:
                                choose_normal_stock_list.append(stock_no)
                        # 强制推荐一个满足要求的空余鞍座
                        infoLogger.info("1.force recommend normal stock")
                        infoLogger.info(choose_normal_stock_list)
                        # 如果有空余的一座一物的鞍座
                        if len(choose_normal_stock_list) != 0:
                            # 选择一个合适的鞍座
                            choose_force_flag_stock = choose_satisfied_width_saddle(choose_normal_stock_list, width)
                            # 没有满足要求的空余鞍座
                            if choose_force_flag_stock == 'null':
                                # 库区里没有合适的鞍座
                                infoLogger.info(
                                    'force recommend empty normal stock,exist empty stock,but no suitable stock')
                                # 强制推荐一个波浪形鞍座
                                infoLogger.info("2.force recommend abnormal stock")
                                infoLogger.info(choose_abnormal_stock_list)
                                # 如果有空余的波浪形鞍座
                                if len(choose_abnormal_stock_list) != 0:
                                    choose_force_wave_stock = choose_satisfied_wave_saddle(choose_abnormal_stock_list,
                                                                                           external_diameter)
                                    # 如果该卷所能放置的波浪形鞍座都放满
                                    if choose_force_wave_stock == []:
                                        infoLogger.info("can not find suitable wave stock")
                                        FLAG = '1011#'
                                        infoLogger.info(FLAG + 'Error')
                                        return FLAG + 'Error'
                                    else:
                                        FLAG = choose_force_wave_stock.split('#')[0] + '#'
                                        recommend_stock_no = choose_force_wave_stock.split('#')[1]
                                        FLAG = '1000#'
                                        infoLogger.info(FLAG + recommend_stock_no)
                                        return FLAG + recommend_stock_no
                                # 如果没有空余的波浪形鞍座
                                else:
                                    infoLogger.info("has no empty wave stock")
                                    FLAG = '1010#'
                                    infoLogger.info(FLAG + 'Error')
                                    return FLAG + 'Error'
                            else:
                                choose_force_stock = choose_force_flag_stock.split('#')[1]
                                infoLogger.info(FLAG + choose_force_stock)
                                FLAG = '1000#'
                                infoLogger.info(FLAG + choose_force_stock)
                                return FLAG + choose_force_stock
                        else:
                            # 如果没有一座一物的鞍座
                            infoLogger.info("has no empty normal stock")
                            infoLogger.info("2.force recommend abnormal stock")
                            infoLogger.info(choose_abnormal_stock_list)
                            # 如果有空余的波浪形鞍座
                            if len(choose_abnormal_stock_list) != 0:
                                choose_force_wave_stock = choose_satisfied_wave_saddle(choose_abnormal_stock_list,
                                                                                       external_diameter)
                                # 如果该卷所能放置的波浪形鞍座都放满
                                if choose_force_wave_stock == []:
                                    infoLogger.info("can not find suitable wave stock")
                                    FLAG = '1011#'
                                    infoLogger.info(FLAG + 'Error')
                                    return FLAG + 'Error'
                                else:
                                    FLAG = choose_force_wave_stock.split('#')[0] + '#'
                                    recommend_stock_no = choose_force_wave_stock.split('#')[1]
                                    FLAG = '1000#'
                                    infoLogger.info(FLAG + recommend_stock_no)
                                    return FLAG + recommend_stock_no
                            # 如果没有空余的波浪形鞍座
                            else:
                                infoLogger.info("has no empty wave stock")
                                FLAG = '1010#'
                                infoLogger.info(FLAG + 'Error')
                                return FLAG + 'Error'
                else:
                    FLAG = recommend_result.split('#')[0] + '#'
                    recommend_stock_no = recommend_result.split('#')[1]
                    FLAG='1000#'
                    infoLogger.info(FLAG + recommend_stock_no)
                    return FLAG + recommend_stock_no
    except Exception, ex:
        errorLogger.error("recommend_stock_position"+str(ex))
        errorLogger.error('error line:' + traceback.print_exc())


# 读取表中任意钢卷号
def read_random_coil_information(table_name):
    cursor = conn_ibm_dbi.cursor()
    strSQL = "SELECT * FROM  %s "%(table_name)
    cursor.execute(strSQL)
    results = cursor.fetchall()
    res = random.choice(results)
    # 钢卷号
    coil_no = res[0]
    coil_width = res[2]
    coil_outdia = res[4]
    coil_name = res[9]
    cursor.close()
    return coil_no,coil_width,coil_outdia,coil_name


if __name__=="__main__":
    recommend_result = recommend_stock_position('18114116200', "C02-1,,,,1,0,0,0, ")
    print recommend_result
    recommend_result_stock = recommend_result.split('#')[1]
    print recommend_result_stock
    # update_has_coil(STOCK_INFORMATION_DATABASE, recommend_result_stock,'18107785100')
